package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.BizException;
import com.itheima.controller.EmpController;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpLogService;
import com.itheima.service.EmpService;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class EmpServiceImpl implements EmpService {

    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprMapper empExprMapper;
    @Autowired
    private EmpLogService empLogService;

    @Autowired
    private EmpController empController;
    /**
     * 分页查询员工列表
     *
     * @param empQueryParam
     * @return
     */
    @Override
    public PageBean pageEmp(EmpQueryParam empQueryParam) {
        ArrayList<Object> objects = new ArrayList<>();
        PageBean pageBean = new PageBean();
        PageHelper.startPage(empQueryParam.getPage(), empQueryParam.getPageSize());
        List<Emp> empList = empMapper.pageEmp(empQueryParam);
        Page<Emp> empPage = (Page<Emp>) empList;
        pageBean.setTotal(empPage.getTotal());
        pageBean.setRows(((Page<Emp>) empList).getResult());
        return pageBean;
    }

    /**
     * 添加员工及工作经历
     *
     * @param emp
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertEmp(Emp emp) {
        try {
            emp.setCreateTime(LocalDateTime.now());
            emp.setUpdateTime(LocalDateTime.now());
            //新增员工数据, 主键返回
            empMapper.insertEmp(emp);
            Integer empId = emp.getId();
            //给员工经历的emp_id赋值
            if (!CollectionUtils.isEmpty(emp.getExprList())) {
                emp.getExprList().forEach(e -> {
                    e.setEmpId(empId);
                });
                empExprMapper.insertEmpExpr(emp.getExprList());
            }
            // int i = 1 / 0;
            //新增员工经历数据
        } finally {
            EmpLog empLog = new EmpLog();
            empLog.setOperateTime(LocalDateTime.now());
            empLog.setInfo(emp.toString());
            empLogService.insertLog(empLog);
        }
    }

    /**
     * 根据ids删除员工
     *
     * @param ids
     */
    @Override
    public void removeEmps(List<Integer> ids) {
        empMapper.deleteByIds(ids);
        empExprMapper.deleteByEmpId(ids);
    }

    /**
     * 根据id查询员工
     *
     * @param id
     * @return
     */
    @Override
    public Emp selectById(Integer id) {
        Emp emp = empMapper.selectById(id);
        return emp;
    }

    /**
     * 修改员工信息
     *
     * @param emp
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateById(Emp emp) {
        // 修改员工表
        empMapper.updateById(emp);

        //删除员工的工作经历
        empExprMapper.deleteByEmpId(List.of(emp.getId()));
        //新增员工经历
        if (!CollectionUtils.isEmpty(emp.getExprList())) {
            emp.getExprList().forEach(e -> {
                e.setEmpId(emp.getId());
            });
            empExprMapper.insertEmpExpr(emp.getExprList());
        }
    }

    /**
     * 根据职位统计员工人数
     *
     * @return
     */
    @Override
    public JobOption getEmpJobData() {
        JobOption option = new JobOption();
        List<Map<String, Object>> mapList = empMapper.getEmpJobData();
        List<Long> dataList = mapList.stream().map(map -> (Long) map.get("total")).collect(Collectors.toList());
        List<String> jobName = mapList.stream().map(map -> (String) map.get("jobName")).collect(Collectors.toList());
        option.setDataList(dataList);
        option.setJobList(jobName);
        return option;
    }

    /**
     * 根据性别统计员工人数
     *
     * @return
     */
    @Override
    public List<NameValueData> getEmpGenderData() {
        List<NameValueData> genderData = empMapper.selectEmpGenderData();
        return genderData;
    }

    /**
     * 查询所有员工
     *
     * @return
     */
    @Override
    public List<Emp> getEmpList() {
        return empMapper.selectEmpList();
    }

    /**
     * 登录校验
     *
     * @param emp
     * @return
     */
    @Override
    public LoginInfo login(Emp emp) {
        // 查询用户名密码是否存在
        Emp dbEmp = empMapper.getEmpByUserName(emp);
        if (dbEmp == null) {
            //用户名不存在
            throw new BizException("用户名错误");
        }
        if (!emp.getPassword().equals(dbEmp.getPassword())) {
            throw new BizException("密码错误");
        }
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setUsername(dbEmp.getUsername());
        loginInfo.setName(dbEmp.getName());
        loginInfo.setId(dbEmp.getId());
        Map<String, Object> map = new HashMap<>();
        map.put("id",dbEmp.getId());
        map.put("username",dbEmp.getUsername());
        map.put("name",dbEmp.getName());
        String jwt = JwtUtils.generateJwt(map);
        loginInfo.setToken(jwt);
        return loginInfo;
    }


}
